package com.gxa.zhonglong.filter;

import com.gxa.zhonglong.common.JsonResult;
import com.gxa.zhonglong.util.ResponseUtil;
import com.gxa.zhonglong.util.StringUtil;
import lombok.SneakyThrows;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName ${NAME}
 * @Author: ws
 * @date 2021/11/2 10:13
 */
//@WebFilter(filterName = "AuthFilter", urlPatterns = "/*")
public class AuthFilter implements Filter {
    @Override
    public void destroy() {
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = ((HttpServletRequest) req);
        HttpServletResponse response = ((HttpServletResponse) resp);

        // 获取URI   通过URI 判断哪些servlet可以直接放行
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);

        //从请求头中获取token
        String token = request.getHeader("Authorization");
        System.out.println(token);

        // 获取session对象，判断session中的token和前端返回的token是否一致
        HttpSession session = request.getSession();
        Object sessionToken = session.getAttribute("token");

        // logout 和 login 请求直接放行

        if ("/user/logout".equals(requestURI) || "/user/login".equals(requestURI)) {

            chain.doFilter(req, resp);

        }else if (!StringUtil.isEmpty(token) && token.equals(sessionToken)) {

            chain.doFilter(req, resp);
            // 修改session保存时间为两小时
            session.setMaxInactiveInterval(60*30);

        }else {
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode("50010");
            jsonResult.setMsg("没有权限，请重新登录");
            ResponseUtil.write(response,jsonResult.getDataMap());
        }



    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
